﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RuleCode.Table;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace chatblog.CommonChat
{
    public partial class ChatManage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = "聊天室后台管理";
            AjaxPro.Utility.RegisterTypeForAjax(typeof (ChatManage ));
            cbuser.dealcookie();
            if (AliApi.appUserId != string.Empty)
            {
                if (Util.ValidateAdmin() == false)
                {
                    Util.RedirectReplacePage(this.Page, "0", ResolveUrl("~/bbs.aspx"));
                    return;
                }
            }    
            if (!IsPostBack)
            {                        
                BindPersonalRoomDataList();
                BindCommonRoomDataList();
            }
        }

        #region 私人聊天室
        private void BindPersonalRoomDataList()
        {                   
            if (Util.ValidateAdmin()&&AliApi .appUserId !=string.Empty )
            {
                cbuser users = cbuser.Find("chatIsOnLine=" + RuleCode.Enum.BooleanEnum.Yes.ToString());
                if (users.Count > 0)
                {
                    PersonalChatWebPager.DataSource = users.MyTable;
                    PersonalChatWebPager.DataBind();
                }                  
            }
            if (PersonalChatWebPager.DataSource == null || PersonalChatWebPager.DataSource.Rows.Count <= 0)
            {
                cbuser users = cbuser.Find("1=2");
                DataTable dTable = users.MyTable.Clone();                 
                PersonalChatWebPager.DataSource = dTable;
                PersonalChatWebPager.DataBind();
            }
        }

        protected void PersonalChatWebPager_PageIndexChanged(object sender, RuleCode.Controls.PageChangedEventArgs e)
        {
            this.PersonalChatWebPager.CurrentPageIndex = e.NewPageIndex;
            BindPersonalRoomDataList();
        }
        #endregion

        #region 公共聊天室
        private void BindCommonRoomDataList()
        {
            DataTable dTable = CommonChatRoomCache.ChatRoomTable.Clone();
            dTable.Columns.Add("NickName", typeof(string));

            if (Util.ValidateAdmin() && AliApi.appUserId != string.Empty)
            {
                foreach (DataRow roomRow in CommonChatRoomCache.ChatRoomTable.Rows)
                {
                    DataRow newRow = dTable.NewRow();                    
                    for (int i = 0; i < dTable.Columns.Count; i++)
                    {                                                    
                        string columnName = dTable.Columns[i].ColumnName;
                        if (columnName == "NickName")
                        {
                            DataRow[] userRows = CommonChatRoomCache.ChatUserTable.Select("UserID='" + roomRow["CreatedBy"].ToString() + "'");
                            newRow[columnName] = (userRows.Length > 0) ?( (userRows[0][columnName].ToString() != "") ? userRows[0][columnName] : userRows[0]["UserID"] ) : "";
                        }
                        else
                        { 
                            newRow [columnName ]= roomRow [columnName ];
                        }                           
                    }
                    dTable.Rows.Add(newRow);
                }
            }
            CommonChatWebPager.DataSource = dTable;
            CommonChatWebPager.DataBind();
        }

        protected void CommonChatWebPager_PageIndexChanged(object sender, RuleCode.Controls.PageChangedEventArgs e)
        {
            this.CommonChatWebPager.CurrentPageIndex = e.NewPageIndex;
            BindCommonRoomDataList();
        }


        #endregion

        #region 辅助方法

        #endregion

        #region Ajax方法
        /// <summary>
        /// 强制下线
        /// </summary>
        /// <param name="userid"></param>
        [AjaxPro .AjaxMethod ]
        public void PersonalForceUnline(string userid)
        {
            if (AliApi.appUserId != string.Empty && Util.ValidateAdmin())
            {
                SqlParameter[] sqlParams = new  SqlParameter [1];
                sqlParams [0]= new SqlParameter ("@userid",userid );
                cbuser user = cbuser.Find("cbuserid=@userid",sqlParams.ToString() );
                if (user.Count > 0)
                {
                    user.chatIsOnLine.Value = RuleCode.Enum.BooleanEnum.No;
                    user.Modify();
                }
            }
        }   
           
        [AjaxPro .AjaxMethod ]
        public void CommonForceChatUnline(string roomType)
        {
            if (AliApi.appUserId != string.Empty && Util.ValidateAdmin())
            {
                DataRow[] roomRows = CommonChatRoomCache.ChatRoomTable.Select("RoomType='"+roomType +"'");
                if (roomRows.Length > 0)
                {
                    string roomId = roomRows[0]["RoomID"].ToString();
                    //移除聊天信息记录
                    DataRow[] chatInfoRows = CommonChatRoomCache.ChatInfoTable.Select("RoomID='"+roomId +"'");
                    foreach (DataRow infoRow in chatInfoRows)
                        CommonChatRoomCache.ChatInfoTable.Rows.Remove(infoRow);
                    //移除聊天用户
                    DataRow[] chatUserRows = CommonChatRoomCache.ChatUserTable.Select("RoomID='" + roomId + "'");
                    foreach (DataRow userRow in chatUserRows)
                        CommonChatRoomCache.ChatUserTable.Rows.Remove(userRow );
                    //移除聊天室
                    CommonChatRoomCache.ChatRoomTable.Rows.Remove(roomRows[0]);
                }
            }
        }  

        [AjaxPro .AjaxMethod ]
        public void CommonForceChatUserUnline(string roomid,string userid)
        {
            if (AliApi.appUserId != string.Empty && Util.ValidateAdmin())
            {
                DataRow[] userRows = CommonChatRoomCache.ChatUserTable.Select("RoomID='"+roomid +"' and UserID='"+userid+"'");
                if (userRows.Length > 0)
                    CommonChatRoomCache.ChatUserTable.Rows.Remove(userRows[0]);
                
                DataRow[] otheruserRows = CommonChatRoomCache.ChatUserTable.Select("RoomID='"+roomid +"'");
                if (otheruserRows.Length <= 0)
                {
                    DataRow[] chatInfoRows = CommonChatRoomCache.ChatInfoTable.Select("RoomID='" + roomid + "'");
                    foreach (DataRow chatInfoRow in chatInfoRows)
                        CommonChatRoomCache.ChatInfoTable.Rows.Remove(chatInfoRow);

                    DataRow[] chatRoomRows = CommonChatRoomCache.ChatRoomTable.Select("RoomID='" + roomid + "'");
                    foreach (DataRow chatRoomRow in chatRoomRows)
                        CommonChatRoomCache.ChatRoomTable.Rows.Remove(chatRoomRow );
                }
            }
        }

        [AjaxPro .AjaxMethod ]
        public string GetCommonChatUsersHTML(string roomID)
        {     
            string html = "对不起，该聊天室没有用户！";
            if (AliApi.appUserId != string.Empty && Util.ValidateAdmin())
            {
                html = string.Empty;
                string roomName =string.Empty ;
                DataRow[] roomRows =CommonChatRoomCache.ChatRoomTable .Select ("RoomID='"+roomID +"'");
                if(roomRows .Length >0)
                    roomName = roomRows [0]["RoomName"].ToString ();

                DataRow[] userRows = CommonChatRoomCache.ChatUserTable.Select("RoomID='"+roomID +"'");
                if(userRows .Length >0)
                    html =string.Empty ;
                string childHtml =string.Empty ;
                foreach (DataRow userRow in userRows )
                {
                    childHtml = "<table onmouseover =\"this.bgColor='lightBlue';\" onmouseout =\"this.bgColor='';\" style=\" width :100%; height :20px\">";
                    childHtml +="<tr>";
                    childHtml +="<td style =\"width :10%; height :20px\"><input  type =\"checkbox\"  id=\""+roomID +"\" /></td>";
                    childHtml +="<td style =\" width :30%; height :20px\">"+roomName+"</td>";
                    childHtml +="<td style =\" width :30%; height :20px\">"+userRow["UserID"].ToString ()+"</td>";
                    childHtml +="<td style =\" width :30%; height :20px\">"+userRow["NickName"].ToString ()+"</td>";
                    childHtml +="</tr></table>";
                    html += childHtml;
                }
            }
            return html;
        }
        #endregion


    }
}
